<?php


namespace App\Service\OrderService\OrderInterfaceService;

/**
 * 售后审核接口
 */

use App\Model\CommodityModel\SupplierCompany;
use App\Model\PssModel\OrderSettlement;
use App\Model\PssModel\OrderSupplierGoods;
use App\Service\AppService\PushOrderSettleMentService;
use App\Service\BaseService;
use App\Model\PssModel\OrderReturnLog;
use App\Service\PushService\BusinessPushService;
use App\Model\PssModel\OrderSupplier;
use App\Service\Code\Normal;
use App\Service\TaskServer\TaskWorker;
use App\Service\OrderService\OrderSupplierEventLogMessageService AS OSELMS;

class OrderAfterSaleVerify extends BaseService
{
    const AFTER_SALE_VERIFY_PASS = 1;
    const AFTER_SALE_VERIFY_REJECT = 2;
    public $channel_order_types=[0,10];
    
    /**
     * 订单售后处理
     */
    public function index( $param = [] )
    {
        if( empty($param['requestData']) ) {
            return Normal::returnCode(Normal::FAIL,"订单数据不能为空");
        }
        $requestData = $param['requestData'];
        if( empty($requestData['orderSn']) ) {
            return Normal::returnCode(Normal::FAIL,"渠道商订单orderSn不能为空");
        }
        
        if( empty($requestData['orderNo']) ) {
            return Normal::returnCode(Normal::FAIL,"供应商订单号orderNo不能为空");
        }
        
        if( !isset($requestData['afterVerifyRemark']) ) {
            return Normal::returnCode(Normal::FAIL,"afterVerifyRemark售后原因不能为空");
        }
        
        if( !isset($requestData['afterVerifyStatus']) ) {
            return Normal::returnCode(Normal::FAIL,"afterVerifyStatus参数缺失");
        }
        
        if( !in_array($requestData['afterVerifyStatus'],[self::AFTER_SALE_VERIFY_REJECT,self::AFTER_SALE_VERIFY_PASS]) ) {
            return Normal::returnCode(Normal::FAIL,"afterVerifyStatus状态值必须在1,2之间");
        }
        
        if( $requestData['afterVerifyStatus'] == self::AFTER_SALE_VERIFY_REJECT && empty($requestData['afterVerifyRemark']) ) {
            return Normal::returnCode(Normal::FAIL,"审核拒绝原因不能为空");
        }

        if( empty($requestData['sys_user_id']) ) {
            return Normal::returnCode(Normal::FAIL,"sys_user_id不能为空");
        }
        
        if( empty($requestData['sys_user_name']) ) {
            return Normal::returnCode(Normal::FAIL,"sys_user_name不能为空");
        }
        
        //查询售后订单
        $res = $this->getSupplierOrderLists($param);
        if( $res['code'] != Normal::SUC ) {
            return $res;
        }
        $res['data']['order'] = $param['requestData'];
        $res['data']['binfo'] = $param['binfo'];
        $res['data']['serviceClass'] = static::class;
        $res['data']['serviceMethod'] = "singleOrderAfterSaleVerify";
        $res = TaskWorker::instance()->addTask($res['data'],'singleOrder');
        $message = implode(",", array_column($res,'msg'));
        $code = array_column($res, 'code');
        if( !in_array(Normal::SUC, $code) ) {
            return Normal::returnCode(Normal::FAIL,"处理完成；【{$message}】",$res);
        }
        return Normal::returnCode(Normal::SUC,"处理完成；【{$message}】",$res);
    }
    
    /**
     * 单个订单售后
     * @param array $param
     */
    public function singleOrderAfterSaleVerify( $param = [] )
    {
        if( empty($param['companyInfo']) || empty($param['supplierOrder']) || empty($param['orderGoods']) || empty($param['order']) || empty($param['binfo']) )
        {
            return Normal::returnCode(Normal::FAIL,"except param companyInfo or supplierOrder or orderGoods or order or binfo");
        }
        
        $companyInfo    = $param['companyInfo'];
        $company_code   = $companyInfo['company_code'];
        $supplierClass  = ucFirst( $companyInfo['OrderDockMode'] == 1 ? 'normal' : $companyInfo['company_code'] );
        $serviceClass   = "App\\Service\\OrderService\\OrderRouteService\\{$supplierClass}";
        if( !class_exists($serviceClass) ) {
            return Normal::returnCode(Normal::FAIL,"{$serviceClass} not existed");
        }
    
        $requestMethod = 'orderAfterSale';
        if( !method_exists($serviceClass,$requestMethod) ) {
            return Normal::returnCode(Normal::FAIL,"{$serviceClass} {$requestMethod} methods not existed");
        }
    
        $supplierOrder      = $param['supplierOrder'];
        $orderGoods         = $param['orderGoods'];
        $order              = $param['order'];
        $binfo              = $param['binfo'];
        $param['apiBody']   = $companyInfo['apiBody'];
        
        //售后审核状态
        $afterVerifyStatus  = (int)$order['afterVerifyStatus'];
        $afterVerifyRemark  = $order['afterVerifyRemark'] ?? '';
        
        //要兼容以前的供应商
        $param['order']['exceptReason'] = $afterVerifyRemark;
        
        //判断是否是顶级云仓进行二审操作权限
        if( $supplierOrder['is_top_system'] != 1 && $supplierOrder['order_push_status'] == 1 ) {
            return Normal::returnCode(Normal::FAIL,"当前系统操作审核订单权限不够，请联系上游供应商系统运营进行操作审核！");
        }
        
        try {
            
            OrderSupplier::instance()->startTrans();
            
            $order_supplier_id = (string)$supplierOrder['id'];
            
            if( $afterVerifyStatus == self::AFTER_SALE_VERIFY_PASS ) {
                $res = OrderReturnLog::instance()->addLog([
                    'order_id'          =>  $order_supplier_id,
                    'type'              =>  OrderReturnLog::AFTER_PASS,
                    'contents'          =>  "管理员:{$order['sys_user_name']}，操作售后审核通过",
                    'system_user_id'    =>  $order['sys_user_id'],
                    'system_user_name'  =>  $order['sys_user_name'],
                ]);
            } else {
                $res = OrderReturnLog::instance()->addLog([
                    'order_id'          =>  $order_supplier_id,
                    'type'              =>  OrderReturnLog::AFTER_REJECT,
                    'contents'          =>  "管理员:{$order['sys_user_name']}，操作售后审核拒绝",
                    'system_user_id'    =>  $order['sys_user_id'],
                    'system_user_name'  =>  $order['sys_user_name'],
                ]);
            }
            
            if( $res['code'] != Normal::SUC ) {
                OrderSupplier::instance()->rollback();
                return $res;
            }
            
            //修改订单状态
            $res = $this->orderAfterSaleVerifyChange($order_supplier_id,$afterVerifyStatus,$afterVerifyRemark);
            if( $res['code'] != Normal::SUC ) {
                OrderSupplier::instance()->rollback();
                return $res;
            }
            
            //推送成功才发起调用供应商接口
            $body = [
                'orderSn'           => $supplierOrder['order_sn'],
                'orderNo'           => $supplierOrder['supplier_csn'],
                'afterVerifyTime'   => date("YmdHis"),
                'afterVerifyStatus' => $afterVerifyStatus,
                'afterVerifyRemark' => $afterVerifyRemark,
            ];
            
            //推送供应商进行售后
            if( $supplierOrder['order_push_status'] == 1 && $afterVerifyStatus == 1 && $supplierOrder['after_supplier_notify_status'] != 1 ) {
                $result_supplier = $serviceClass::instance()->$requestMethod($param);
                $result_code = $result_supplier['code'] == Normal::SUC ? 1 : 2;
                $result_msg  = $result_supplier['msg'] ?? '请求失败';
                
                //如果通知供应商失败了，这个时候要将云仓里面订单状态修改为审核拒绝
                if( $result_code == 2 ) {
                    $res = $this->orderAfterSaleVerifyChange($order_supplier_id,2,$result_msg);
                    if( $res['code'] != Normal::SUC ) {
                        OrderSupplier::instance()->rollback();
                        return $res;
                    }
                    //如果为第三方渠道则直接返回云仓错误信息,让操作员自行处理
                    if($binfo['is_channel'] == 2){
                        OrderSupplier::instance()->rollback();
                        return $result_supplier;
                    }
                }
                
                OrderSupplier::instance()->where('id',$order_supplier_id)->update([
                    'after_supplier_notify_status'  => $result_code,
                    'after_supplier_notify_remark'  => $result_msg
                ]);
                if ( $result_code != 1 ){
                    $body['afterVerifyStatus'] = $result_code;
                    $body['afterVerifyRemark'] = $result_msg;
                }

               
            } 
            
            //开始对上游进行售后(云仓商城的订单售后需要审核),或者是下游直接审核通过
            //产生了订单货款结算记录，才进行恢复结算数据操作
            //一定要是通知下游渠道body 里面 afterVerifyStatus =1 才写入售后结算数据
            if( $body['afterVerifyStatus'] == self::AFTER_SALE_VERIFY_PASS && $supplierOrder['isRecoverSettleMentMoney'] ) {
                //写入结算售后退款数据
                $param['mode'] = PushOrderSettleMentService::SETTLEMENT_MODE_AFTER_SALE;
                if( $supplierOrder['is_channel_settlement'] == 1 || $supplierOrder['is_supplier_settlement'] ==1 ) {
                    $res = PushOrderSettleMentService::instance()->addOrderSettleMentLog($param);
                    if( $res['code'] != Normal::SUC ) {
                        OrderSupplier::instance()->rollback();
                        return $res;
                    }
                }
                OSELMS::instance()->publish(
                    $order_supplier_id,
                    OSELMS::EVENT_TYPE_ORDER_SETTLEMENT_AFTERSALE,
                    '订单发起售后结算'
                    );
            }
            
            //发起推送渠道商接口数据
            if( $binfo['is_support_aftersale_verify'] == 1 && $supplierOrder['after_channel_notify_status'] != 1 && in_array($supplierOrder['order_type'],$this->channel_order_types) )
            {
                $result_channel = BusinessPushService::instance()->pushMessage('OrderAfterSaleVerifyNotify',$binfo,$body);
                $result_msg = $result_channel['msg'];
                if( $result_channel['code'] != Normal::SUC ) {
                    OrderSupplier::instance()->rollback();
                    OrderSupplier::instance()->where('id',$order_supplier_id)->update([
                        'after_channel_notify_status'  => 2,
                        'after_channel_notify_remark'  => $result_msg
                    ]);
                    return Normal::returnCode(Normal::FAIL,"渠道商接收售后审核结果失败『{$result_msg}』");
                }
            
                OrderSupplier::instance()->where('id',$order_supplier_id)->update([
                    'after_channel_notify_status'  => 1,
                    'after_channel_notify_remark'  => $result_msg
                ]);
            }
            
            OrderSupplier::instance()->commit();
            
            //写入订单日志行为
            OSELMS::instance()->publish(
                $order_supplier_id,
                $afterVerifyStatus == self::AFTER_SALE_VERIFY_PASS ? OSELMS::EVENT_TYPE_ORDER_AFTER_SALE_PASS : OSELMS::EVENT_TYPE_ORDER_AFTER_SALE_REJECT,
                $afterVerifyStatus == self::AFTER_SALE_VERIFY_PASS ? "审核通过":"审核拒绝:[{$afterVerifyRemark}]"
                );
            
            //恢复库存
            if( $afterVerifyStatus == self::AFTER_SALE_VERIFY_PASS ) {
                OrderCancel::instance()->recoverGoodsStock($param);
            }
            
            return Normal::returnCode(Normal::SUC,"审核操作成功",[
                'orderItem' => [
                    'orderSn'  => $supplierOrder['order_sn'],
                    'orderNo'  => $supplierOrder['supplier_csn'],
                ]
            ]);
            
        } catch ( \Throwable $th) {
            OrderSupplier::instance()->rollback();
            return Normal::returnCode(Normal::FAIL,"二审操作失败，内部异常『{$th->getMessage()},{$th->getFile()},{$th->getLine()}』 ");
        }
    }
    
    /**
     * 获取供应商列表
     * @param array $param
     */
    public function getSupplierOrderLists( $param = [] )
    {
        $bid = $param['binfo']['bid'];
        $requestData = $param['requestData'];
        $supplierOrderList = OrderSupplier::instance()
        ->select(OrderSupplier::instance()->order_fields)
        ->where('bid',$bid)
        ->whereIn('order_status',[1,2])
        ->where('order_sn',$requestData['orderSn'])
        ->where('supplier_csn',$requestData['orderNo'])
        ->where('after_sale_status',1)
        ->get()
        ->toArray();
        if( empty($supplierOrderList) ) {
            return Normal::returnCode(Normal::FAIL,"当前订单不存在或已售后");
        }
        
        //获取订单商品
        $osids  = array_column($supplierOrderList,'id');
        //获取订单商品
        $orderGoods = OrderSupplierGoods::instance()
        ->select(OrderSupplierGoods::instance()->goods_fields)
        ->where('bid',$bid)
        ->whereIn('order_id',$osids)
        ->get()
        ->toArray();
        
        if( empty($orderGoods) ) {
            return Normal::returnCode(Normal::FAIL,"获取订单数据失败");
        }
    
        //获取供应商结算数据
        $settlementOrderList = OrderSettlement::instance()
        ->select([
            'id',
            'order_id',
        ])
        ->where('bid',$bid)
        ->whereIn('order_id',$osids)
        ->where('settlement_type',2)
        ->where('settlement_mode',1)
        ->get()
        ->toArray();
        $settlementOrderList = array_column($settlementOrderList, null,'order_id');
    
        $supplierOrderList = array_map(function( & $value ) use ($settlementOrderList){
            //如果存在结算下单数据，则进行退款操作
            $value['isRecoverSettleMentMoney'] = isset($settlementOrderList[$value['id']]) ? true : false;
            return $value;
        },$supplierOrderList);
        
        $newOrderGoods = [];
        foreach ($orderGoods as $item ) {
            $newOrderGoods[$item['order_id']][] = $item;
            unset($item);
        }

        //获取供应商清单信息
        $companyIds = array_unique(array_column($supplierOrderList,'company_id'));
        $SupplierCompanyLists = SupplierCompany::instance()->getSupplierListByIds($companyIds);
        $SupplierCompanyLists = array_column($SupplierCompanyLists, null,'company_id');

        return Normal::returnCode(Normal::SUC,"订单数据获取成功",[
            'supplierOrderList' => $supplierOrderList,
            'newOrderGoods' => $newOrderGoods,
            'suppplierList' => $SupplierCompanyLists
        ]);
    }
    
    /**
     * 售后审核接口
     * @param string $order_supplier_id
     * @param int $after_verify_status
     * @param string $after_verify_remark
     * @return mixed
     */
    public function orderAfterSaleVerifyChange(string $order_supplier_id,int $after_verify_status,string $after_verify_remark = null)
    {
        $time = time();
        $where = [
            ['id','=',$order_supplier_id],
            ['after_sale_status','=',self::AFTER_SALE_VERIFY_PASS],
        ];
        $data = [
            'after_verify_status'   => $after_verify_status,
            'after_verify_remark'   => $after_verify_remark,
            'after_verify_time'     => $time,
            'md'                    => $time
        ];
        
        //审核拒绝的情况下,需要把是否售后恢复到未发起售后的状态
        if( $after_verify_status == self::AFTER_SALE_VERIFY_REJECT ) {
            $data['after_sale_status'] = 0;
            $data['after_sale_remark'] = '二审拒绝';
        }
        
        $res = OrderSupplier::instance()->edit($where,$data);
        if( !$res ) {
            return Normal::returnCode(Normal::FAIL,"当前订单售后审核状态变更失败，请检查是否已经审核通过!");
        }
        return Normal::returnCode(Normal::SUC,"操作成功");
    }
}